import {Component, OnInit, ViewChild} from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import {MatDatepickerInputEvent, MatDialog} from '@angular/material';
import { AssetaddComponent } from '../assetadd/assetadd';
import { ConfirmDialogComponent } from '../confirmDialog/confirmDialog';
import { AssetService } from '../../service/assetService';
import { Asset, AssetStatus, StatusNameMap } from '../../models/Asset';
import { Department } from '../../models/Department';
import { tap } from 'rxjs/operators';
import { AssetType } from '../../models/AssetType';
import { User } from '../../models/User';
import {IActionMapping, ITreeOptions, TreeComponent} from 'angular-tree-component';
import { DepartmentService } from '../../service/departmentService';
import { UserService } from '../../service/userService';
import { Loginauth } from '../../service/loginauth';
import { environment } from '../../environments/environment';
import { FormControl } from '@angular/forms';
import { Moment } from 'moment';
import { RepairaddComponent } from '../repairadd/repairadd';
import { Router } from '@angular/router';
import { Deliver } from '../../models/Deliver';
import * as moment from 'moment';
declare var $: any;
@Component({
  templateUrl: './assetlist.html',
  styleUrls: ['./assetlist.css']
})
export class AssetlistComponent implements OnInit {
  options: ITreeOptions = {};
  nodes: any = [];
  assettypeName: string;
  environment = environment;
  typetree: boolean = false;
  @ViewChild(TreeComponent)
  private tree: TreeComponent;
  assets: Asset[];
  asset: Asset;
  page = 1;
  pageSize = 10;
  total: number;
  departmentid: number;
  AssetStatus = AssetStatus;
  StatusNameMap = StatusNameMap;
  type = AssetStatus.ALL;
  users: User[];
  departments: Department[];
  assetTypes: AssetType[];
  baseurl: string;
  isAdmin: boolean;
  isGuest: boolean;  //是否为游客
  orders: string[] = [];
  orderType: number;
  orderWords: string = '排序';
  outQRCode: boolean = false;
  excel: boolean = false;
  appearSearch: boolean = false;
  start_createDate: any;
  end_createDate: any;
  imgAppear: boolean;
  codeAppear: boolean;
  imgUrl1: string;
  imgUrl2: string;
  imgUrl3: string;
  haveimg2: boolean = false;
  haveimg3: boolean = false;
  fronturl: string = '';
  behindurl: string = '/api/assetinfo/getlist?outQRCode=true&pageSize=999999';
  url: string = '';
  excelurl: string = '';
  beginCtrl = new FormControl();
  endCtrl = new FormControl();
  count: number = 0;
  allassets: Asset[];
  actionMapping: IActionMapping = {
    mouse: {
      click: (tree, node, $event) => {
        this.asset.assetType = node.data.GDZCLB_DM;
        this.assettypeName = node.data.GDZCLBMC;
        this.typetree = false;
      }
    }
  };
  colsone = ['rukuNum', 'assetStatus', 'assetCode', 'assetName'];
  colstwo = ['assetType', 'createDate', 'brand', 'source', 'version', 'sourceComefrom',
    'assetPrice', 'buyDate', 'snNum', 'assetImg', 'user', 'department', 'address', 'seatNum', 'invoiceNum', 'qrcode', 'remark'];
  colsthree = ['operate'];
  constructor(private route: ActivatedRoute,
              private dialog: MatDialog,
              private assetService: AssetService,
              private departmentService: DepartmentService,
              private userService: UserService,
              private loginauthService: Loginauth,
              private router: Router
             ) {

  }
  ngOnInit() {
    this.fronturl = 'http://' + location.host;
    this.url = this.fronturl + this.behindurl;
    this.excelurl = this.fronturl + this.behindurl;
    this.loginauthService.checkAdmin().subscribe((isAdmin: boolean) => {
      this.isAdmin = isAdmin;
      if (!this.isAdmin) {
        this.colstwo = ['assetType', 'createDate', 'brand', 'source', 'version', 'sourceComefrom',
          'assetPrice', 'buyDate', 'snNum', 'assetImg', 'user', 'department', 'address', 'seatNum', 'invoiceNum', 'qrcode', 'remark'];
      }
    })
    //是否为游客
    this.loginauthService.checkGuest().subscribe((isGuest: boolean) => {
      this.isGuest = isGuest;
      if (this.isGuest) {
        this.colstwo = [ 'assetType', 'createDate', 'brand', 'source', 'version', 'sourceComefrom',
          'assetPrice', 'buyDate', 'snNum', 'assetImg', 'user', 'department', 'address', 'seatNum', 'invoiceNum', 'qrcode', 'remark'];
      }
    })
    this.asset = new Asset();
    this.asset.sysUser = new User();
    this.asset.sysDepartment = new Department();
    this.baseurl = 'http://file.sxycy.cn:8081';
    this.update(this.page).subscribe();
    this.route.data.subscribe((res: {assetType: AssetType[]}) => {
      this.assetTypes = res.assetType;
    })
    for (let i = 0; i < this.assetTypes.length; i++) {
      this.nodes.push({GDZCLBMC: this.assetTypes[i].GDZCLBMC, GDZCLB_DM: this.assetTypes[i].GDZCLB_DM});
    }
    this.nodes.forEach((node, index) => {
      node.children = this.assetTypes[index].children;
    })
    this.options = {displayField: 'GDZCLBMC', idField: 'GDZCLB_DM', actionMapping: this.actionMapping };
    this.departmentService.getAllDepartments().subscribe((res) => {
      this.departments = res.res;
    })
  }

  onChangeType(assetType: number) {
    this.type = assetType;
    this.update(this.page, assetType).subscribe();
  }
  onSelectbuyDate1(event: MatDatepickerInputEvent<Moment>) {
    this.asset.buyDate = event.value.toDate();
    this.asset.buyDateShow = new FormControl(event.value);
  }
  onSelectcreateDate1(event: MatDatepickerInputEvent<Moment>) {
    this.asset.createDate = event.value.toDate();
    this.asset.createDateShow = new FormControl(event.value);
  }
  changeDepartment(departmentId) {
    this.departmentid = departmentId;
    this.getUsers();
  }
  getUsers() {
    this.userService.getUsers(1, 20, this.departmentid).subscribe((res) => {
      this.users = res.res;
    })
  }
  bigImg(imgUrl1, imgUrl2, imgUrl3) {
    this.imgUrl1 = this.baseurl + imgUrl1;
    if (imgUrl2 !== null && imgUrl2 !== 'null' && imgUrl2) {
      this.haveimg2 = true;
      this.imgUrl2 = this.baseurl + imgUrl2;
    } else {
      this.haveimg2 = false;
    }
    if (imgUrl3 !== null && imgUrl3 !== 'null' && imgUrl3) {
      this.haveimg3 = true;
      this.imgUrl3 = this.baseurl + imgUrl3;
    } else {
      this.haveimg3 = false;
    }
    this.imgAppear = true;
  }
  bigCode(imgUrl1) {
    console.log(imgUrl1);
    this.imgUrl1 = this.baseurl + imgUrl1;
    this.codeAppear = true;
  }
  closeImg() {
    this.imgAppear = false;
    this.imgUrl1 = '';
    this.imgUrl2 = '';
  }
  closeCode() {
    this.codeAppear = false;
  }
  onopenAdd() {
    const dialogRef = this.dialog.open(AssetaddComponent, {
      width: '900px',
      height: '550px',
      data: {
        assetTypes: this.assetTypes
      }
    });
    dialogRef.afterClosed().subscribe((result) => {
      this.update(this.page).subscribe();
    });
  }
  onSwitchDate(_: Moment) {
     this.start_createDate = this.beginCtrl.value;
     this.end_createDate = this.endCtrl.value;
  }
  trackById(index: number, item: any) {
    return item.id;
  }
  bigsearch() {
    this.appearSearch = false;
    this.update(this.page, this.type).subscribe();
  }
  appearSearchbox() {
    this.appearSearch = true;
  }
  closesearch() {
    this.appearSearch = false;
  }
  update(page, assetType?: number) {
    this.count = 0;
    const options: any = {};
    const type = assetType;
    if (Number(type) === 0) {
      this.asset.assetStatus = assetType;
      this.asset.repairStatus = null;
      this.colsone = ['rukuNum', 'assetStatus', 'assetCode', 'assetName'];
    }
    if (type === 2) {
      this.asset.repairStatus = 2;
      this.asset.assetStatus = null;
      this.colsone = ['rukuNum', 'repairStatus', 'assetCode', 'assetName'];
    }
    if (type === 1) {
      this.asset.repairStatus = null;
      this.asset.assetStatus = 1;
      this.colsone = ['rukuNum', 'assetStatus', 'assetCode', 'assetName'];
    }
    if (type === 4) {
      this.asset.repairStatus = 3;
      this.asset.assetStatus = null;
      this.colsone = ['rukuNum', 'repairStatus', 'assetCode', 'assetName'];
    }
    if (type === 5) {
      this.asset.repairStatus = null;
      this.asset.assetStatus = null;
      this.colsone = ['rukuNum', 'assetStatus', 'assetCode', 'assetName'];
    }
    if (this.asset.assetName) {options.assetName = this.asset.assetName; }
    if (this.orders) {options.orders = this.orders; }
    if (String(this.asset.assetStatus) && String(this.asset.assetStatus) !== 'null') {options.assetStatus = this.asset.assetStatus; }
    if (this.asset.repairStatus) {options.repairStatus = this.asset.repairStatus; }
    if (this.asset.assetCode) {options.assetCode = this.asset.assetCode; }
    if (this.asset.assetVersion) {options.assetVersion = this.asset.assetVersion; }
    if (this.asset.sourceComefrom) {options.sourceComefrom = this.asset.sourceComefrom; }
    if (this.asset.assetBrand) {options.assetBrand = this.asset.assetBrand; }
    if (this.asset.sysUser.username) {options.assetName = this.asset.sysUser.username; }
    if (this.asset.address) {options.address = this.asset.address; }
    if (this.asset.seatNum) {options.seatNum = this.asset.seatNum; }
    if (this.asset.snNum) {options.snNum = this.asset.snNum; }
    if (this.asset.invoiceNum) {options.invoiceNum = this.asset.invoiceNum; }
    if (this.asset.remark) {options.remark = this.asset.remark; }
    if (this.asset.money) {options.money = this.asset.money; }   //新加
    if (this.asset.assetType) {options.assetType = this.asset.assetType; }
    if (this.asset.source) {options.source = this.asset.source; }
    if (this.asset.sysDepartment.id) {options.assetDepartmentId = this.asset.sysDepartment.id; }
    if (this.asset.sysUser.id) {options.assetUserId = this.asset.sysUser.id; }
    if (this.start_createDate) {const start = this.start_createDate.toDate(); options.start_createDate = start; }
    if (this.end_createDate) {const end = this.end_createDate.toDate(); options.end_createDate = end ; }
    if (this.outQRCode) {options.outQRCode = this.outQRCode; }
    if (this.excel) {options.excel = this.excel; }
    this.assetService.getAssets(page, 999999, options).subscribe((res) => {
      this.allassets = res.res;
      this.allassets.forEach((result) => {
        this.count += Number(result.assetPrice);

      })
      this.count = Math.ceil(this.count);
    })
    return this.assetService.getAssets(page, this.pageSize, options).pipe(tap((res) => {
      this.assets = res.res;
      this.total = res.total;
      this.page = page;
    }));

  }

  onPageChanged(page: number) {
    this.page = page;
    this.update(page).subscribe();
  }
  onOrderChange(orderType) {
    this.orderType = orderType;
    switch (this.orderType) {
      case 2:
        this.orderWords = '最早入库';
        this.orders = [];
        this.orders.push('createDate|asc');
        break;
      case 3:
        this.orderWords = '设备价格';
        this.orders = [];
        this.orders.push('assetPrice|asc');
        break;
      case 1:
      default:
        this.orderWords = '最近入库';
        this.orders.push('createDate|desc');
    }
    this.update(this.page).subscribe();
  }
  onOpenEdit(asset: Asset) {
    const dialogRef = this.dialog.open(AssetaddComponent, {
      width: '900px',
      height: '550px',
      data: {
        asset: asset,
        assetTypes: this.assetTypes
      }
    });
    dialogRef.afterClosed().subscribe((result) => {
      this.update(this.page).subscribe();
    });
  }

  onDelete(id: string) {
    const dialogRef = this.dialog.open(ConfirmDialogComponent, {
      width: '400px',
      height: '200px',
      data: {message: '确认删除？'}
    });
    dialogRef.afterClosed().subscribe((result) => {
      if (result) {
        this.assetService.del(id).subscribe((res) => {
          if (res.success) {
            this.update(this.page).subscribe();
          }
        });
      }
    });
  }
  onopenReapir() {
    const dialogRef = this.dialog.open(RepairaddComponent, {
      width: '900px',
      height: '550px',

    });
    dialogRef.afterClosed().subscribe((result) => {
      this.update(this.page).subscribe();
    });
  }

  search() {
    this.update(this.page, this.type).subscribe();
  }

  showtypeTree() {
    this.typetree = !this.typetree;
  }
  hidetree() {
    this.typetree = false;
  }
  reset() {
    this.asset = new Asset();
    this.asset.sysUser = new User();
    this.asset.sysDepartment = new Department();
    this.assettypeName = '';
    this.beginCtrl = new FormControl();
    this.endCtrl = new FormControl();
    this.start_createDate = false;
    this.end_createDate = false;

  }
  onExportCode() {
    this.outQRCode = true;
    if (this.asset.assetName) {this.url += `&assetName=${this.asset.assetName}`; }
    if (String(this.asset.assetStatus) && String(this.asset.assetStatus) !== 'null' && String(this.asset.assetStatus) !== 'undefined') { this.url += `&assetStatus=${this.asset.assetStatus}`; }
    if (this.asset.repairStatus) {this.url += `&repairStatus=${this.asset.repairStatus}`; }
    if (this.asset.assetCode) {this.url += `&assetCode=${this.asset.assetCode}`; }
    if (this.asset.assetVersion) {this.url += `&assetVersion=${this.asset.assetVersion}`; }
    if (this.asset.sourceComefrom) {this.url += `&sourceComefrom=${this.asset.sourceComefrom}`; }
    if (this.asset.assetBrand) {this.url += `&assetBrand=${this.asset.assetBrand}`; }
    if (this.asset.seatNum) {this.url += `&seatNum=${this.asset.seatNum}`; }
    if (this.asset.snNum) {this.url += `&snNum=${this.asset.snNum}`; }
    if (this.asset.invoiceNum) {this.url += `&invoiceNum=${this.asset.invoiceNum}`; }
    if (this.asset.remark) {this.url += `&remark=${this.asset.remark}`; }
    if (this.asset.assetType) {this.url += `&assetType=${this.asset.assetType}`; }
    if (this.asset.source) {this.url += `&source=${this.asset.source}`; }
    if (this.asset.sysDepartment.id) {this.url += `&assetDepartmentId=${this.asset.sysDepartment.id}`; }
    if (this.asset.sysUser.id) {this.url += `&assetUserId=${this.asset.sysUser.id}`; }
    const a = window.open(this.url);
    const loop = setInterval(() => {
      if (a.closed) {
        clearInterval(loop);
        parent.location.reload();
      }
    }, 1);
  }

  onExportTable() {
    this.excel = true;
    if (this.asset.assetName) {this.excelurl += `&assetName=${this.asset.assetName}`; }
    if (String(this.asset.assetStatus) && String(this.asset.assetStatus) !== 'null' && String(this.asset.assetStatus) !== 'undefined') { this.excelurl += `&assetStatus=${this.asset.assetStatus}`; }
    if (this.asset.repairStatus) {this.excelurl += `&repairStatus=${this.asset.repairStatus}`; }
    if (this.asset.assetCode) {this.excelurl += `&assetCode=${this.asset.assetCode}`; }
    if (this.asset.assetVersion) {this.excelurl += `&assetVersion=${this.asset.assetVersion}`; }
    if (this.asset.sourceComefrom) {this.excelurl += `&sourceComefrom=${this.asset.sourceComefrom}`; }
    if (this.asset.assetBrand) {this.excelurl += `&assetBrand=${this.asset.assetBrand}`; }
    if (this.asset.seatNum) {this.excelurl += `&seatNum=${this.asset.seatNum}`; }
    if (this.asset.snNum) {this.excelurl += `&snNum=${this.asset.snNum}`; }
    if (this.asset.invoiceNum) {this.excelurl += `&invoiceNum=${this.asset.invoiceNum}`; }
    if (this.asset.remark) {this.excelurl += `&remark=${this.asset.remark}`; }
    if (this.asset.assetType) {this.excelurl += `&assetType=${this.asset.assetType}`; }
    if (this.asset.source) {this.excelurl += `&source=${this.asset.source}`; }
    if (this.asset.sysDepartment.id) {this.excelurl += `&assetDepartmentId=${this.asset.sysDepartment.id}`; }
    if (this.asset.sysUser.id) {this.excelurl += `&assetUserId=${this.asset.sysUser.id}`; }
    console.log(this.excelurl);
    const a = window.open(this.excelurl);
    const loop = setInterval(() => {
      if (a.closed) {
        clearInterval(loop);
        parent.location.reload();
      }
    }, 1);

  }
}
